package com.example.bluetoothdemo;

import static android.content.ContentValues.TAG;

import android.app.*;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.*;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.google.android.gms.common.api.PendingResult;

public class BackgroundMusicService extends Service {
    MediaPlayer player;

    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.start);
        player.setLooping(false);
        player.setVolume(0, 0);
        Log.d(TAG, "onCreate: BackgroundMusicService");
        play();
    }

    public void stop() {
        player.pause();
    }

    public void play() {
        player.start();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: BackgroundMusicService");
        buildNotification();
        return Service.START_STICKY;
    }

    private void buildNotification() {
        final int NOTIFICATION_ID = 200;
        String CHANNEL_ID = "channel_01";
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setOngoing(true)
                .setContentTitle("title")
                .setContentText("artist")
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setStyle(
                        new androidx.media.app.NotificationCompat.MediaStyle()
                )
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .build();

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        notificationManager.notify(NOTIFICATION_ID, notification);
        Log.d(TAG, "buildNotification: startForeground");
        startForeground(NOTIFICATION_ID, notification);
    }


    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }


    public class ServiceBinder extends Binder {
        BackgroundMusicService getService() {
            return BackgroundMusicService.this;
        }
    }

    private final IBinder myBinder = new ServiceBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }




}
